#_*_ coding:UTF-8 _*_
__author__ = 'shede333'


import os
import mutagen.id3
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3


def get_input_path(prompt):
    input_path = raw_input(prompt)
    input_path = os.path.expanduser(input_path)
    if os.path.isdir:
        return input_path
    else:
        print "path '%s' is invalid" % input_path
        exit()
        return None


def update_mp3_name(sub_path, name=None):
    print "start handle %s" % sub_path
    id3_info = MP3(sub_path, ID3=EasyID3)
    sub_list = name.split('-')
    tag_title = None
    tag_artist = None
    if len(sub_list) is 2:
        tag_artist = sub_list[0].strip()
        tag_title = sub_list[1].strip()
        print "update artist"
    else:
        tag_title = name

    id3_info['title'] = tag_title.decode('utf-8')
    if tag_artist is not None:
        id3_info['artist'] = tag_artist.decode('utf-8')

    id3_info.save()


def show_error_list(sub_list):
    if len(sub_list) is 0:
        print "\n *** all finish, no error ***"
        return

    print "\n *** error list:\n"
    for sub_error in sub_list:
        print sub_error


def main():
    source_path = get_input_path("input source dir path:")
    dir_list = os.listdir(source_path)
    error_list = []
    for file_name in dir_list:
        if not file_name.endswith(".mp3"):
            # 只对MP3做处理
            continue
        file_path = os.path.join(source_path, file_name)
        try:
            update_mp3_name(file_path, name=file_name)
        except Exception, e:
            print "\n ### error:%s\n" % file_path, e
            error_list.append(file_path)

    show_error_list(error_list)


if __name__ == '__main__':
    main()